package ext.acae2.dms.web.input;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import jcifs.smb.SmbFile;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.ptc.ddl.wtutil.IBAHelper;

import wt.enterprise.RevisionControlled;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.locks.LockHelper;
import wt.log4j.LogR;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.pom.Transaction;
import wt.session.SessionHelper;
import wt.util.WTProperties;
import wt.vc.baseline.ManagedBaseline;
import ext.acae2.dms.bean.DocumentBean;
import ext.acae2.dms.bean.EPMDocumentBean;
import ext.acae2.dms.bean.EPMMemberLinkBean;
import ext.acae2.dms.bean.EPMReferenceLinkBean;
import ext.acae2.dms.bean.PartBean;
import ext.acae2.dms.load.LoadXml;
import ext.acae2.dms.parse.ParseXml;
import ext.acae2.dms.parse.ParseXmlToMap;
import ext.acae2.dms.parse.wc9.ParseImportList;
import ext.acae2.mail.EmailUtility;
import ext.acae2.mail.util.MailUtility;
import ext.acae2.util.FileUtil;
import ext.acae2.util.IBAUtil;
import ext.acae2.util.MappingUtil;
import ext.acae2.util.ParameterUtil;
import ext.acae2.util.StringUtil;
import ext.acae2.util.UGHostUtil;
import ext.acae2.dms.parse.wc9.*;

public class UploadProcessor {

	private static final Logger LOGGER = LogR.getLogger(UploadProcessor.class
			.getName());
	
	public static final String EMAIL_TITLE="EMAIL_TITLE";
	public static final String EMAIL_CONTENT="EMAIL_CONTENT";
	public static final String EAMIL_ATTACHEMENT="EAMIL_ATTACHEMENT";
	
	private static String rmiHost;
	private static String protocol;
	private static String webappName;
	
	static {
		try {
			WTProperties props = WTProperties.getLocalProperties();
			rmiHost = props.getProperty("java.rmi.server.hostname");
			protocol = props.getProperty("wt.webserver.protocol");
			webappName = props.getProperty("wt.webapp.name");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<String> process(HttpServletRequest request) {

		LOGGER.debug("> Start process");

		long start = System.currentTimeMillis();
		
		List<String> returnList = new ArrayList<String>();
		Transaction trans = new Transaction();
		
		String filePath = "";

		try {
			// String procOid = request.getParameter("procOid");
			// ReferenceFactory rf = new ReferenceFactory();
			// Persistable p = rf.getReference(procOid).getObject();

			List<DiskFileItem> parameters = new WebUtil().parseRequest(request);
			String transactionSubmitFlag = new WebUtil().getFormFieldData(
					parameters, "transactionSubmitFlag");
			if (StringUtils.isNotBlank(transactionSubmitFlag)) {
				trans = null;
			}
			if (trans != null) {
				trans.start();
			}
			LOGGER.debug("parameters: " + parameters.size());

			String supplier = new WebUtil().getSupplierName(parameters);
			LOGGER.debug("supplier: " + supplier);

			// 1. Upload file to server.
			LOGGER.debug("---------- Step 1 start ----------");
			File serverFile = new UploadFileProcessor().upload(parameters);
			LOGGER.debug("---------- Step 1 end ----------");

			// 2. Unzip file on server side.
			LOGGER.debug("---------- Step 2 start ----------");
			filePath = serverFile.getAbsolutePath();
			String xmlPath = "";
			if (filePath.toUpperCase().endsWith(".ZIP")) {
				xmlPath = new UnzipProcessor().unzip(serverFile);
			} else if (filePath.toUpperCase().endsWith(".RAR")) {
				xmlPath = new UnrarProcessor().unrar(serverFile);
			}
			LOGGER.debug("xmlPath: " + xmlPath);
			LOGGER.debug("---------- Step 2 end ----------");
			LOGGER.debug("supplier: " + supplier);

			LOGGER.debug("---------- Step 3 start ----------");
			// 3. Parse XML.
			Map<String, List> resultMap = null;
			if(supplier.equals("614")){
				resultMap = ParseImportList.readtxt(xmlPath);
				ext.acae2.dms.parse.wc9.LoadXml.run(resultMap);
			}else{
				
				resultMap = new ParseXml().execute(xmlPath,supplier);
				LOGGER.debug("---------- Step 4 start ----------");
				// 4. Create Object in Windchill.

				//LoadXml.run(resultMap);
				LOGGER.debug("---------- Step 4 end ----------");

				// List activityList = new ArrayList();
				// activityList = WorkflowHelper.getActivities((WfProcess)p,
				// activityList);
				// Iterator iterator= activityList.iterator();
				// while (iterator.hasNext()) {
				// WfAssignedActivity wfactivity = (WfAssignedActivity) iterator
				// .next();
				// if (wfactivity.getName().indexOf("下载导入") > -1) {
				// TaskConfigrationHelper.setActivityVariableValue(wfactivity,
				// "isImported", true);
				// break;
				// }
				// }
				
				if(UGHostUtil.EXE.equals("Y")){
					int endIndex = xmlPath.lastIndexOf(".");
					String url1 = xmlPath.substring(0, endIndex);
					
					File localFile = new File(url1);
					File[] localFiles = localFile.listFiles();
					
					WTUser user = (WTUser)SessionHelper.manager.getPrincipal();
					String userName = user.getName();
					String time = System.currentTimeMillis() + "";
					String path = UGHostUtil.UGTEMP + userName + File.separator + time + File.separator;
					
					SmbFile ugtemp = new SmbFile(path);
					if(!ugtemp.exists()){
						ugtemp.mkdirs();
					}
					
					boolean smbPut = FileUtil.smbPut(localFiles, path);
					if(smbPut != true){
						returnList.add("上传文件有误");
						return returnList;
					}
					
					List<EPMMemberLinkBean> epmMemberLinkList = resultMap.get(ParameterUtil.EPMMEMBERLINK);
					List<EPMReferenceLinkBean> epmReferenceLinkList = resultMap.get(ParameterUtil.EPMREFERENCELINK);
					boolean execute = UGClient.execute(epmMemberLinkList, epmReferenceLinkList, userName, time);
					if(execute != true){
						returnList.add("转换模型有误");
						return returnList;
					}
					
					boolean smbGet = FileUtil.smbGet(url1 + File.separator, path);
					if(smbGet != true){
						returnList.add("下载文件有误");
						return returnList;
					}
					
					boolean delFolder = FileUtil.delFolder(path);
					if(delFolder != true){
						returnList.add("删除文件有误");
						return returnList;
					}
				}
				
				LoadXml.run(resultMap);
				
			}
			
			if (trans != null) {
				trans.commit();
			}

			List<PartBean> partBeanList = resultMap.get(ParameterUtil.PARTBEAN);
			
			for (int i = 0; i < partBeanList.size(); i++) {
				returnList.add("部件" + partBeanList.get(i).getNumber() + "创建成功！");
					if (StringUtil.isEmpty(partBeanList.get(i).getMap().get("drawingNo"))) {
						returnList.add("部件 " + partBeanList.get(i).getNumber()
								+ " 的 图号 的值不存在，请确认");
					}
					if (StringUtil.isEmpty(partBeanList.get(i).getMap().get("characterType"))) {
						returnList.add("部件 " + partBeanList.get(i).getNumber()
								+ " 的 特性分类 的值不存在，请确认");
					}
					if (StringUtil.isEmpty(partBeanList.get(i).getMap().get("mass"))) {
						returnList.add("部件 " + partBeanList.get(i).getNumber()
								+ " 的 质量 的值不存在，请确认");
					}
					if (StringUtil.isEmpty(partBeanList.get(i).getMap().get("unit"))) {
						returnList.add("部件 " + partBeanList.get(i).getNumber()
								+ " 的 质量单位 的值不存在，请确认");
					}
					if (StringUtil.isEmpty(partBeanList.get(i).getMap().get("model"))) {
						returnList.add("部件 " + partBeanList.get(i).getNumber()
								+ " 的 型号 的值不存在，请确认");
					}
					if (StringUtil.isEmpty(partBeanList.get(i).getMap().get("Design"))) {
						returnList.add("部件 " + partBeanList.get(i).getNumber()
								+ " 的 设计 的值不存在，请确认");
					}
			}
//			List<DocumentBean> docList = resultMap
//					.get(ParameterUtil.DOCUMENTBEAN);
//			for (int i = 0; i < docList.size(); i++) {
//				returnList.add("文件" + docList.get(i).getNumber() + "创建成功！");
//			}
			
			int endIndex = filePath.lastIndexOf(".");
			boolean deleteDir = FileUtil.deleteDir(new File(filePath.substring(0, endIndex)));
			if(deleteDir != true){
				returnList.add("删除文件夹有误");
				return returnList;
			}
			if (serverFile.exists()) {
				boolean delete = serverFile.delete();
				if(delete != true){
					returnList.add("删除文件有误");
					return returnList;
				}
			}
			
			LOGGER.debug("---------- Step 3 end ----------");

			LOGGER.debug("导入用时(秒)：" + (System.currentTimeMillis() - start)/1000 );
			
			sendEmail(returnList, filePath, true, "");
			
		} catch (Exception e) {
			e.printStackTrace();
			sendEmail(returnList, filePath, false, e.getMessage());
			if (trans != null) {
				trans.rollback();
			}
			return returnList;
		}

		LOGGER.debug("> End process");
		return returnList;
	}
	
	public static void sendEmail(List<String> returnList, String filePath, boolean b, String str) {
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			
			WTPrincipal principal = SessionHelper.manager.getPrincipal();
			List<WTPrincipal> toPrincipals = new ArrayList<WTPrincipal>();
			toPrincipals.add(principal);
		    
			String subject = "";
			if(b == true){
				subject = filePath + " 数据包导入成功";
			}else{
				subject = filePath + " 数据包导入失败";
			}
			
//			String url = protocol + "://" + rmiHost + "/" + webappName
//					+ "/app/#ptc1/tcomp/infoPage?ContainerOid=OR%3Awt.pdmlink.PDMLinkProduct%3A41585&oid=OR%3Awt.folder.SubFolder%3A10211172&u8=1";
			
			String content = "<table>";
			for (int i = 0; i < returnList.size(); i++) {
				content += "<tr>" + returnList.get(i) + "</tr>";
			}
			if(b == true){
				content += "以上相关部件已成功导入,请查阅。";
			}else{
				content += "数据包导入失败,请联系管理员。";
			}
//			content += "<a href=\"" + url + "\" target=\"_blank\">" + subject + "</a>";
			content += "</table>";
			content += str;
			
			map.put(EmailUtility.EMAIL_TITLE, subject);
			map.put(EmailUtility.EMAIL_CONTENT, content);
			
			EmailUtility.sendEmail(map, toPrincipals, null);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
